package com.tdcoding.chat.action.common;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.tdcoding.chat.action.BaseAction;
import com.tdcoding.chat.entities.RequestInfo;

import io.netty.channel.Channel;

/**
 * 
 * action的集合，在系统初始化的时候会把所有的action都初始化一遍，
 * 	缓存在这里，每个Action用一个ActionItem描述
 * @author wellsa
 *
 */
public class ActionMapper {
	private static ActionMapper actionMapper;
	private Map<String, ActionContext> contextMapper;
	
	public static ActionMapper getInstance(){
		if (actionMapper==null) {
			actionMapper=new ActionMapper();
		}
		return actionMapper;
	}
	
	public ActionMapper() {
		contextMapper= new HashMap<String, ActionContext>();
	}
	
	/**
	 * 
	 * 根据请求名获得相应的ActionContext
	 * @param referer
	 * @return
	 */
	public ActionContext getActionContext(String actionName) {
		return contextMapper.get(actionName);
	}
	
	/**
	 * 新增一个ActionContext
	 * @param actionClass
	 * @param actionName
	 * @param actionfilter
	 * @throws Exception
	 */
	public void addActionContext(String actionName, BaseAction baseAction,ArrayList<ActionFilter> lBaseFilters) throws Exception{
		try {
//			Logger.println(this, "addActionContext",actionName,baseAction);
			ActionContext actionContext =getActionContext(actionName);
			if(actionContext!= null) {
				return;
			}
//			Logger.println(this, "addActionContext~",actionName,baseAction);
			actionContext = new ActionContext();
			actionContext.setBaseAction(baseAction);
			Method method = baseAction.getClass().getMethod(actionName,new Class<?>[]{ Channel.class,RequestInfo.class});
			actionContext.setMethod(method);
			actionContext.setlBaseFilters(lBaseFilters);
			contextMapper.put(actionName, actionContext);
		} catch (Exception e) {
			throw e;
		}
	}

	public void cleatActionMapping(){
		if (contextMapper!=null) {
			contextMapper.clear();
		}
	}
}
